﻿SET NOCOUNT ON;

DECLARE @CurrentSqlRestartedDateTime SMALLDATETIME

SELECT @CurrentSqlRestartedDateTime = [msdb].[sys].[databases].[create_date] 
FROM [msdb].[sys].[databases] 
WHERE ([msdb].[sys].[databases].[name] = 'tempdb')

IF(NOT EXISTS(SELECT [TABLE_NAME] FROM msdb.information_schema.tables WHERE [TABLE_NAME] = 'SQLRestartMonitor')) BEGIN
	CREATE TABLE [msdb].[dbo].[SQLRestartMonitor]
	(
		[SqlRestarted] BIT, 
		[SqlRestartedDateTime] SMALLDATETIME
	)

	INSERT INTO [msdb].[dbo].[SQLRestartMonitor]
	(
		[SqlRestarted],
		[SqlRestartedDateTime] 
	)
	VALUES 
	(
		0, 
		@CurrentSqlRestartedDateTime
	);

END
ELSE BEGIN

	DECLARE @SqlRestartedDateTime SMALLDATETIME

	SELECT @SqlRestartedDateTime = MAX([SqlRestartedDateTime]) FROM [msdb].[dbo].[SQLRestartMonitor]

	IF(@SqlRestartedDateTime != @CurrentSqlRestartedDateTime)
	INSERT INTO [msdb].[dbo].[SQLRestartMonitor]
	(
		[SqlRestarted],
		[SqlRestartedDateTime] 
	)
	VALUES 
	(
		1, 
		@CurrentSqlRestartedDateTime
	);
END

SELECT TOP 1 
	[SqlRestarted],
	[SqlRestartedDateTime]
FROM [msdb].[dbo].[SQLRestartMonitor]
ORDER BY [SqlRestartedDateTime] DESC
